package com.ng.framework.view.desktop.filters;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.ng.framework.persistence.NGGenericPersistence;
import com.ng.framework.persistence.NGSearchCriteria;
import com.ng.framework.persistence.NGSearchParameter;
import com.ng.framework.view.desktop.NGGUIUtils;
import com.ng.framework.view.desktop.NGTablePanel;

public class NGFiltersPanel<T, P extends NGGenericPersistence<T>> extends JPanel implements ActionListener {
	
	private static final long serialVersionUID = 496988957134806360L;
	
	private P persistence;
	private NGTablePanel<T, P> tablePanel;
	private List<NGFilter> nGFilters;

	private JButton buttonBuscar;

	public NGFiltersPanel(List<NGFilter> nGFilters, NGTablePanel<T, P> tablePanel, P persistence) {
		this.nGFilters = nGFilters;
		this.tablePanel = tablePanel;
		this.persistence = persistence;
		
		this.initComponents();
		
		this.buildGui();
	}
	
	private void initComponents() {
		this.buttonBuscar = NGGUIUtils.createTextButton("Buscar", this);
	}
	
	private void buildGui() {
		this.setLayout(new GridBagLayout());
		
		for(int i = 0; i < nGFilters.size(); i++) {
			NGFilter ngFilter = nGFilters.get(i);
			
			this.add(new JLabel(ngFilter.getName() + ":"), new GridBagConstraints(0, i, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, i == nGFilters.size() - 1 || nGFilters.size() == 1 ? 0 : 5, 5), 0, 0));
			this.add(ngFilter, new GridBagConstraints(1, i, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, i == nGFilters.size() - 1 || nGFilters.size() == 1 ? 0 : 5, 5), 0, 0));
		}
		
		this.add(buttonBuscar, new GridBagConstraints(2, nGFilters.size() - 1, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		NGSearchCriteria criteria = new NGSearchCriteria();
		
		for(NGFilter nGFilter : nGFilters) {
			List<NGSearchParameter> searchParameters = nGFilter.getSearchParameters();
			
			if(searchParameters != null) {
				for(NGSearchParameter searchParameter : searchParameters) {
					criteria.addNGSearchParameter(searchParameter);
				}				
			}
		}
		
		tablePanel.setData(persistence.getAll(criteria));
	}

}
